package com.hh.base.widget.common

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import com.hh.base.R
import com.hh.base.databinding.LayoutTitleViewBinding

/**
 * Create By hHui on 2025/4/8 10:58
 *
 * @description 顶部title
 */
class TitleView : ConstraintLayout {
    private lateinit var titleViewBinding: LayoutTitleViewBinding

    /**
     * 右侧图片点击事件
     */
    var rightImageClickListener: TitleClickListener? = null

    /**
     * 中间title文字
     */
    var title: String = ""
        set(value) {
            field = value
            titleViewBinding.txtTitle.text = value
        }

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context, attrs, defStyle
    ) {
        initText(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initText(context, attrs)
    }

    init {
        initView()
    }

    private fun initText(context: Context, attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TitleView)
        //标题
        var mText = ""
        if (typedArray.getText(R.styleable.TitleView_title) != null) {
            mText = typedArray.getText(R.styleable.TitleView_title).toString()
        }
        val isSupportBack = typedArray.getBoolean(R.styleable.TitleView_isSupportBack, true)
        val rightImageDrawable = typedArray.getDrawable(R.styleable.TitleView_rightImg)
        typedArray.recycle()
        title = mText
        //是否显示返回按钮
        titleViewBinding.imgBack.visibility = if (isSupportBack) View.VISIBLE else View.GONE

        if (rightImageDrawable == null) {
            titleViewBinding.imgRight.visibility = View.GONE
        } else {
            titleViewBinding.imgRight.visibility = View.VISIBLE
            titleViewBinding.imgRight.setImageDrawable(rightImageDrawable)
        }

    }

    private fun initView() {
        titleViewBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.layout_title_view, this, true)

        titleViewBinding.imgBack.setOnClickListener {
            (context as? AppCompatActivity)?.finish()
        }
        titleViewBinding.imgRight.setOnClickListener {
            rightImageClickListener?.onClick()
        }
    }

    interface TitleClickListener {
        fun onClick()
    }
}